/*
 * Main.java
 *
 * Created on 28-mei-2009 11:35:36;
 */

package org.sunspotworld;

import com.sun.spot.peripheral.Spot;
import com.sun.spot.sensorboard.EDemoBoard;
import com.sun.spot.sensorboard.peripheral.ISwitch;
import com.sun.spot.sensorboard.peripheral.ITriColorLED;
import com.sun.spot.peripheral.radio.RadioFactory;
import com.sun.spot.peripheral.radio.IRadioPolicyManager;
import com.sun.spot.io.j2me.radiostream.*;
import com.sun.spot.io.j2me.radiogram.*;
import com.sun.spot.util.*;

import java.io.*;
import javax.microedition.io.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

/**
 * The startApp method of this class is called by the VM to start the
 * application.
 * 
 * The manifest specifies this class as MIDlet-1, which means it will
 * be selected for execution.
 */
public class Main extends MIDlet {


    protected void startApp() throws MIDletStateChangeException {
        new BroadcastReceiveThread(this).start();
    }

    protected void pauseApp() {
        // This is not currently called by the Squawk VM
    }

    /**
     * Called if the MIDlet is terminated by the system.
     * I.e. if startApp throws any exception other than MIDletStateChangeException,
     * if the isolate running the MIDlet is killed with Isolate.exit(), or
     * if VM.stopVM() is called.
     * 
     * It is not called if MIDlet.notifyDestroyed() was called.
     *
     * @param unconditional If true when this method is called, the MIDlet must
     *    cleanup and release all resources. If false the MIDlet may throw
     *    MIDletStateChangeException  to indicate it does not want to be destroyed
     *    at this time.
     */
    protected void destroyApp(boolean unconditional) throws MIDletStateChangeException {
    }

    public synchronized  void recieveBroadcastMessage(Datagram datagram, RadiogramConnection rgCon) {
        String message = "";

        try{
            message = datagram.readUTF();

            replyWithDatagram("5", datagram, rgCon);
     
        }catch(IOException ioe){
            ioe.printStackTrace();
        }
    }

    private void replyWithDatagram(String message, Datagram adressSourceDG, RadiogramConnection rgCon){
        Datagram dgreply;

        try {
            dgreply = rgCon.newDatagram(rgCon.getMaximumLength());
        } catch (IOException ex) {
            ex.printStackTrace();
            return;
        }

        try{
            dgreply.reset();        // reset stream pointer
            dgreply.setAddress(adressSourceDG.getAddress());

            dgreply.writeUTF(message);

            rgCon.send(dgreply);

        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }
}
